//
//  VideoViewController.m
//  iFarmacia
//
//  Created by Jose Lino on 12/8/10.
//  Copyright 2011 Skymedia. All rights reserved.
//

#import "VideoViewController.h"
#import "FavoritoViewControlle.h"
#import "SobreViewControlle.h"
#import "MapaviewController.h"
#import "ARController.h"


@implementation VideoViewController

@synthesize arController;
@synthesize bussolaView, ARView;

#define CENTRO self.arController.overlayView.bounds.size.width/2, (self.arController.overlayView.bounds.size.height - 100)/2
#define CENTRO_LABEL_INV 180 * M_PI / 180.0
#define CENTRO_LABEL_COR 360 * M_PI / 180.0

- (void)loadView{
	
	myDados = [[Dados alloc] init];
	arrFarm = [myDados readFarmFromDatabase];
	//self.view.frame = CGRectMake(0, 0, 320, 400);
	UIView *myView = [[UIView alloc] init];
	myView.frame = CGRectMake(0, 0, 320, 320);
	
	self.arController = [[ARController alloc] initWithViewController:self];

	locationManager=[[CLLocationManager alloc] init];
	locationManager.desiredAccuracy = kCLLocationAccuracyBest;
	locationManager.delegate=self;
	
	// Listen for changes in device orientation
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientationDidChange:) name: UIDeviceOrientationDidChangeNotification object:nil];
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];	
	arrDistancia = [[NSMutableArray alloc] init];
	[self initWithObject:arrFarm];
	[self criaTabBar];
}

- (void)viewDidAppear:(BOOL)animated {
	//[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(iniciarAR) userInfo:nil repeats:NO];
	[super viewDidAppear:animated];
	//Iniciar Camera
	[self.arController presentModalARControllerAnimated:NO];
} 

- (void)viewWillAppear:(BOOL)animated {
	
	[super viewWillAppear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	
	orientation = interfaceOrientation;
	
	locationManager=[[CLLocationManager alloc] init];
	locationManager.desiredAccuracy = kCLLocationAccuracyBest;
	locationManager.delegate=self;
	[locationManager startUpdatingLocation];
	
	return YES;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)dealloc {
	[arController release];
    [super dealloc];
}


#pragma mark View
-(void) criaTabBar{
	
	CGRect tabBarRect = CGRectMake(0, 430, 320, 50);
	UITabBar *myTabBar = [[UITabBar alloc] initWithFrame:tabBarRect];
	tabBarView = myTabBar;
	
	tabBarView.delegate = self;
	
	//TabBar Buttons
	btMapa = [[UITabBarItem alloc] initWithTitle:@"Mapa" image:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"103-map" ofType:@"png"]] tag:0];
	btVideo = [[UITabBarItem alloc] initWithTitle:@"Vídeo" image:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"71-compass" ofType:@"png"]] tag:1];
	btFavoritos = [[UITabBarItem alloc] initWithTitle:@"Favoritos" image:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"28-star" ofType:@"png"]] tag:2];
	btSobre= [[UITabBarItem alloc] initWithTitle:@"Sobre" image:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"09-chat-2" ofType:@"png"]] tag:3];
	// Collect the items in a temporary array.
	NSArray *items = [NSArray arrayWithObjects:btMapa, btVideo, btFavoritos, btSobre, nil];
	
	// Pass the items to the toolbar.
	[tabBarView  setItems:items];
	[tabBarView setSelectedItem:btVideo];

	[self.arController.overlayView addSubview:tabBarView];
	
}

- (void) tabBar: (UITabBar *) tabBar didSelectItem: (UITabBarItem *) item{
	

	[self.arController release];
	[self.bussolaView removeFromSuperview];
	//tabBarView.selectedItem = item;
	FavoritoViewControlle *favoritos = [[FavoritoViewControlle alloc] initWithNibName:@"FavoritoViewControlle" bundle:nil];
	SobreViewControlle *sobre = [[SobreViewControlle alloc] initWithNibName:@"SobreViewControlle" bundle:nil];
	MapaviewController *mapa = [[MapaviewController alloc] initWithNibName:@"MapaviewController" bundle:nil];
	
	switch (item.tag) {
		case 0:
			
			//navigation = [[UINavigationController alloc] initWithNibName:@"MapaviewController" bundle:nil];
			navigation = [[UINavigationController alloc] initWithRootViewController:mapa ];
			break;
		case 1:
			
			//[atualNavigationController popToViewController: [atualNavigationController.viewControllers objectAtIndex:1] animated:YES];
			break;
		case 2:
		
			navigation = [[UINavigationController alloc] initWithRootViewController:favoritos ];
			break;
		case 3:
		
			navigation = [[UINavigationController alloc] initWithRootViewController:sobre ];
			break;
		default:
			break;
	}
	
	[navigation setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
	[self presentModalViewController:navigation animated:YES];
	[navigation release];
	
		[self.arController.rootController dismissModalViewControllerAnimated:YES];
}

-(void) viewAR
{
	if (!arView) {
		
		NSDictionary *masterDict = [[NSDictionary alloc] init];
		
		for (int i=0; i<[DictDados count]; i++) {
			
			masterDict = [DictDados objectForKey:[NSString stringWithFormat:@"%d", i]];

			//Loop com os dados do ponto
			tempLocation = [[CLLocation alloc] initWithLatitude:[[masterDict objectForKey:@"latitude"] floatValue] longitude:[[masterDict objectForKey:@"longitude"] floatValue]];
			tempCoordinate = [[ARGeoCoordinate alloc] initWithCoordiante:tempLocation andTitle:farmObj.farmNome];
			
			//Chama função para calcular a distancia dos pontos
			//NSLog(@"Pontos de distancia Lat:%f - Lon:%f /  Lat:%f Lon:%f", latitudeAtual, longitudeAtual, fLat, fLon);
			double distancia = [[masterDict objectForKey:@"distancia"] floatValue];
			tempCoordinate.coordinateTitle = [masterDict objectForKey:@"nome"];
			tempCoordinate.coordinateDistance = distancia;
			tempCoordinate.coordinateInclination = M_PI/distancia;
			[self.arController addCoordinate:tempCoordinate animated:NO];
			[tempLocation release];
		}
	}
}

#pragma mark -
#pragma mark Calculo de Distancia

-(double) ToRad:(double)nVal
{
	return nVal * (M_PI/180);
}

-(double) CalculateDistance:(double) nLat1 Lon:(double) nLon1 Lat:(double) nLat2 Long:(double) nLon2 indice:(int)onde
{	
	
	double nRadius = 6378; // Earth's radius in Kilometers
	
	// Get the difference between our two points then convert the difference into radians
	double nDLat = [self ToRad:(nLat2 - nLat1)];  
	double nDLon = [self ToRad:(nLon2 - nLon1)]; 
	
	nLat1 =  [self ToRad:(nLat1)];
	nLat2 =  [self ToRad:(nLat2)];
	
	double nA =	pow ( sin(nDLat/2), 2 ) + cos(nLat1) * cos(nLat2) * pow ( sin(nDLon/2), 2 );
	
	double nC = 2 * atan2( sqrt(nA), sqrt( 1 - nA ));
	double nD = nRadius * nC;
	
	NSString *distancia = [NSString stringWithFormat:@"%.2f %d",nD, onde];
	
	[arrDistancia addObject:[distancia copy]];
	return nD;
	
}

#pragma mark -
#pragma mark View Bússula

-(void)viewBussola{
	
	
	CGRect bussolaViewCG = CGRectMake(0, 0, 320, 480);
	self.bussolaView = [[UIView alloc] initWithFrame:bussolaViewCG];
	self.bussolaView.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"fundoBussola.png"]];
	[self.arController.overlayView addSubview:self.bussolaView];
	
	//Start the compass updates.
	[locationManager startUpdatingHeading];
	locationManager.headingFilter = 5; // 5 degrees

	CGRect myImageSeta = CGRectMake(bussolaView.bounds.size.width / 2, bussolaView.bounds.size.height / 2, 320.0f, 56.0f); 
	
	//centro bússola
	CGRect myImageRect = CGRectMake((bussolaView.bounds.size.width - 70) / 2, (bussolaView.bounds.size.height - 70) / 2, 70.0f, 70.0f); 
	myImage = [[UIImageView alloc] initWithFrame:myImageRect]; 
	[myImage setImage:[UIImage imageNamed:@"bussola.png"]]; 
	myImage.opaque = YES; 
	
	arrSeta = [[NSMutableArray alloc] init];
	NSDictionary *masterDict = [[NSDictionary alloc] init];

	for (int i=0; i<[DictDados count]; i++) {

		masterDict = [DictDados objectForKey:[NSString stringWithFormat:@"%d", i]];
		NSLog(@"nome: %@", [masterDict objectForKey:@"nome"]);
		UILabel *tituloLabel = [[[UILabel alloc] initWithFrame:CGRectMake(200, 20, 100, 15)] autorelease];
		tituloLabel.text = [masterDict objectForKey:@"nome"];
		tituloLabel.backgroundColor = [UIColor clearColor];
		tituloLabel.textColor = [UIColor whiteColor];
		tituloLabel.font = [UIFont boldSystemFontOfSize:10];
		
		UILabel *metroLabel = [[[UILabel alloc] initWithFrame:CGRectMake(260, 35, 40, 10)] autorelease];
		NSString *metrosString = [NSString stringWithFormat:@"%.1f Km", [self CalculateDistance:latitudeAtual Lon:longitudeAtual Lat:[[masterDict objectForKey:@"latitude"] floatValue] Long:[[masterDict objectForKey:@"longitude"] floatValue] indice:i]];
		metroLabel.text = metrosString;
		metroLabel.backgroundColor = [UIColor clearColor];
		//metroLabel.textColor = [[UIColor alloc] initWithRed:255 green:255 blue:204 alpha:1];
		metroLabel.textColor = [UIColor yellowColor];
		metroLabel.font = [UIFont boldSystemFontOfSize:9];
		
		//create the button
		UIButton *buttonToque = [UIButton buttonWithType:UIButtonTypeCustom];
		buttonToque.backgroundColor = [UIColor clearColor];
		[buttonToque setFrame:CGRectMake(180, 0, 140, 56)];
		[buttonToque addTarget:self action:@selector(nextPage:)
			  forControlEvents:UIControlEventTouchUpInside];
		buttonToque.tag = [[masterDict objectForKey:@"id"] intValue];
		
		switch (i) {
			case 0:
				setaImage0 = [[UIImageView alloc] initWithFrame:myImageSeta]; 
				setaImage0.image = [UIImage imageNamed:@"setaBussola2.png"]; 
				setaImage0.userInteractionEnabled = YES;
				
				tituloLabel0 = tituloLabel;
				metrosLabel0 = metroLabel;
				
				[setaImage0 addSubview:tituloLabel0];
				[setaImage0 addSubview:metrosLabel0];
				[setaImage0 addSubview:buttonToque];
				
				break;
			case 1:
				setaImage1 = [[UIImageView alloc] initWithFrame:myImageSeta]; 
				[setaImage1 setImage:[UIImage imageNamed:@"setaBussola2.png"]]; 
				setaImage1.userInteractionEnabled = YES;
				
				tituloLabel1 = tituloLabel;
				metrosLabel1 = metroLabel;
				
				[setaImage1 addSubview:tituloLabel1];
				[setaImage1 addSubview:metrosLabel1];

				[setaImage1 addSubview:buttonToque];
				
				
				break;
			case 2:
				setaImage2 = [[UIImageView alloc] initWithFrame:myImageSeta]; 
				[setaImage2 setImage:[UIImage imageNamed:@"setaBussola2.png"]]; 
				tituloLabel2.userInteractionEnabled = YES;
				
				tituloLabel2 = tituloLabel;
				metrosLabel2 = metroLabel;
				
				[setaImage2 addSubview:tituloLabel2];
				[setaImage2 addSubview:metrosLabel2];
				
				[setaImage2 addSubview:buttonToque];
				
				break;
			case 3:
				setaImage3 = [[UIImageView alloc] initWithFrame:myImageSeta]; 
				[setaImage3 setImage:[UIImage imageNamed:@"setaBussola2.png"]]; 
				setaImage3.userInteractionEnabled = YES;
				
				tituloLabel3 = tituloLabel;
				metrosLabel3 = metroLabel;
				
				[setaImage3 addSubview:tituloLabel3];
				[setaImage3 addSubview:metrosLabel3];
				
				[setaImage3 addSubview:buttonToque];
				
				break;
			case 4:
				setaImage4 = [[UIImageView alloc] initWithFrame:myImageSeta]; 
				[setaImage4 setImage:[UIImage imageNamed:@"setaBussola2.png"]];
				setaImage4.userInteractionEnabled = YES;
				
				tituloLabel4 = tituloLabel;
				metrosLabel4 = metroLabel;
				
				[setaImage4 addSubview:tituloLabel4];
				[setaImage4 addSubview:metrosLabel4];
				
				[setaImage4 addSubview:buttonToque];
				
				break;
			case 5:
				setaImage5 = [[UIImageView alloc] initWithFrame:myImageSeta]; 
				[setaImage5 setImage:[UIImage imageNamed:@"setaBussola2.png"]]; 
				setaImage5.userInteractionEnabled = YES;
				
				tituloLabel5 = tituloLabel;
				metrosLabel5 = metroLabel;
				
				[setaImage5 addSubview:tituloLabel5];
				[setaImage5 addSubview:metrosLabel5];
				
				[setaImage5 addSubview:buttonToque];
				
				break;
			case 6:
				setaImage6 = [[UIImageView alloc] initWithFrame:myImageSeta]; 
				[setaImage6 setImage:[UIImage imageNamed:@"setaBussola2.png"]]; 
				setaImage6.userInteractionEnabled = YES;
				
				tituloLabel6 = tituloLabel;
				metrosLabel6 = metroLabel;
				
				[setaImage6 addSubview:tituloLabel6];
				[setaImage6 addSubview:metrosLabel6];
				
				[setaImage6 addSubview:buttonToque];
				
				break;
			case 7:
				setaImage7 = [[UIImageView alloc] initWithFrame:myImageSeta]; 
				[setaImage7 setImage:[UIImage imageNamed:@"setaBussola2.png"]]; 
				setaImage7.userInteractionEnabled = YES;
				
				tituloLabel7 = tituloLabel;
				metrosLabel7 = metroLabel;
				
				[setaImage7 addSubview:tituloLabel7];
				[setaImage7 addSubview:metrosLabel7];
				
				[setaImage7 addSubview:buttonToque];
				
				break;
			case 8:
				setaImage8 = [[UIImageView alloc] initWithFrame:myImageSeta]; 
				[setaImage8 setImage:[UIImage imageNamed:@"setaBussola2.png"]];
				setaImage8.userInteractionEnabled = YES;
				
				tituloLabel8 = tituloLabel;
				metrosLabel8 = metroLabel;
				
				[setaImage8 addSubview:tituloLabel8];
				[setaImage8 addSubview:metrosLabel8];
				
				[setaImage8 addSubview:buttonToque];
				
				break;
			case 9:
				setaImage9 = [[UIImageView alloc] initWithFrame:myImageSeta]; 
				[setaImage9 setImage:[UIImage imageNamed:@"setaBussola2.png"]]; 
				setaImage9.userInteractionEnabled = YES;
				
				tituloLabel9 = tituloLabel;
				metrosLabel9 = metroLabel;
				
				[setaImage9 addSubview:tituloLabel9];
				[setaImage9 addSubview:metrosLabel9];
				
				[setaImage9 addSubview:buttonToque];
				
				break;
			default:
				break;
		}
	}
	
	[self.bussolaView addSubview:myImage];
	
}


// retorna o angulo de 'from' para 'to' em radians
//      0 = 'to' is due east
//      45 = nne
//      90 = due north
//      135 = nnw
//      -45 = sse
//      -90 = s
//      -135 = ssw
// returns the angle from 'from' to 'to' in radians from the positive x axis (zero is due east; increasing counterclockwise)
- (double)computeAngleFrom:(CLLocation*)from  to:(CLLocation*)to
{
	// what's the angle to the item?
	double itemLatRad = to.coordinate.latitude / 180.0 / M_PI ;
	double itemLonRad = to.coordinate.longitude / 180.0 / M_PI;
	double ourLatRad = from.coordinate.latitude / 180.0 / M_PI;
	double ourLonRad = from.coordinate.longitude /180.0 / M_PI;
	
	// protect against the (unlikely) possibilty that they're at the exact same point
	if((itemLonRad - ourLonRad) == 0.0)
		itemLonRad += 0.0001;
	
	
	// For any real arguments x and y not both equal to zero,
	// atan2(y, x) is the angle in radians between the positive x-axis of a plane and the point given by the coordinates (x, y) on it.
	// The angle is positive for counter-clockwise angles (upper half-plane, y > 0),
	// and negative for clockwise angles (lower half-plane, y < 0).
	double x = (itemLonRad - ourLonRad);
	double y = (itemLatRad - ourLatRad);
	// on the iphone, atan2 takes args in y,x
	// (on some platforms it's the other way around!)
	double angleFromUsToItem = atan2( y, x);
	
	return angleFromUsToItem;
}

- (BOOL)locationManagerShouldDisplayHeadingCalibration:(CLLocationManager *)manager {
	return YES;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading {	
	
	
	//[manager stopUpdatingLocation];
	double headingInDegreesClockwiseFromNorth = newHeading.trueHeading;
	double headingInDegreesClockwiseFromDueEast = fmod( headingInDegreesClockwiseFromNorth - 90.0,  360.0);
	double headingInDegreesCounterclockwiseFromDueEast = fmod( 360.0 - headingInDegreesClockwiseFromDueEast, 360.0);
	lastKnownHeadingInRadians = headingInDegreesCounterclockwiseFromDueEast * M_PI / 180.0;
	
	float mHeading = newHeading.trueHeading;

	NSDictionary *masterDict = [[NSDictionary alloc] init];
	for (int i=0; i<[DictDados count]; i++) {

		masterDict = [DictDados objectForKey:[NSString stringWithFormat:@"%d", i]];
		CLLocation *itemLocation = [[[CLLocation alloc] initWithLatitude:[[masterDict objectForKey:@"latitude"] floatValue] longitude:[[masterDict objectForKey:@"longitude"] floatValue]] autorelease];
		CLLocation *myLocation = [[[CLLocation alloc] initWithLatitude:latitudeAtual longitude:longitudeAtual] autorelease];
		double angleFromUsToItemCounterClockwise = [self computeAngleFrom:myLocation to:itemLocation];
		
		//	NSString *nomeFantasia = [[masterArrayBU2 objectAtIndex:i] objectForKey:@"nomeFantasia"];
		double asDegrees0 = angleFromUsToItemCounterClockwise / 2.0 / M_PI * 360.0;
		double asDegrees1 = lastKnownHeadingInRadians / 2.0 / M_PI * 360.0;
		double asDegrees = (asDegrees0 + asDegrees1) / 100;
		
		if (asDegrees > 3) {
			asDegrees = asDegrees - 3.00;
		}
		if (asDegrees0 <= - 0) {
			asDegrees = -asDegrees;
		}

		float anguloItem = (angleFromUsToItemCounterClockwise - lastKnownHeadingInRadians -  M_PI_2) * -1.0 - M_PI;

		switch (i) {
			case 0:
				[setaImage0 removeFromSuperview];
				[bussolaView addSubview:setaImage0];
				
				setaImage0.transform = CGAffineTransformIdentity;
				setaImage0.center = CGPointMake(CENTRO);
				setaImage0.transform = CGAffineTransformMakeRotation(anguloItem);
				
				if(asDegrees >= -1.50 && asDegrees <= -0.01)
				{
					tituloLabel0.transform = CGAffineTransformIdentity;
					tituloLabel0.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
					metrosLabel0.transform = CGAffineTransformIdentity;
					metrosLabel0.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
				}
				else if(asDegrees >= 0.00 && asDegrees <= 1.50)
				{
					tituloLabel0.transform = CGAffineTransformIdentity;
					tituloLabel0.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
					metrosLabel0.transform = CGAffineTransformIdentity;
					metrosLabel0.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
				}
				else if(asDegrees >= 1.50 && asDegrees <= 2.99)
				{
					tituloLabel0.transform = CGAffineTransformIdentity;
					tituloLabel0.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);
					metrosLabel0.transform = CGAffineTransformIdentity;
					metrosLabel0.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);
				}
				else if(asDegrees <= -1.50 || asDegrees >= -2.99)
				{
					tituloLabel0.transform = CGAffineTransformIdentity;
					tituloLabel0.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);
					metrosLabel0.transform = CGAffineTransformIdentity;
					metrosLabel0.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);	
				}
				
				break;
			case 1:
				
				[bussolaView addSubview:setaImage1]; 
				
				setaImage1.transform = CGAffineTransformIdentity;
				setaImage1.center = CGPointMake(CENTRO);
				setaImage1.transform = CGAffineTransformMakeRotation(anguloItem);
				
				if(asDegrees >= -1.50 && asDegrees <= -0.01)
				{
					tituloLabel1.transform = CGAffineTransformIdentity;
					tituloLabel1.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
					metrosLabel1.transform = CGAffineTransformIdentity;
					metrosLabel1.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
				}
				else if(asDegrees >= 0.00 && asDegrees <= 1.50)
				{
					tituloLabel1.transform = CGAffineTransformIdentity;
					tituloLabel1.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
					metrosLabel1.transform = CGAffineTransformIdentity;
					metrosLabel1.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
				}
				else if(asDegrees >= 1.50 && asDegrees <= 2.99)
				{
					tituloLabel1.transform = CGAffineTransformIdentity;
					tituloLabel1.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);
					metrosLabel1.transform = CGAffineTransformIdentity;
					metrosLabel1.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);
				}
				else if(asDegrees <= -1.50 || asDegrees >= -2.99)
				{
					tituloLabel1.transform = CGAffineTransformIdentity;
					tituloLabel1.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);
					metrosLabel1.transform = CGAffineTransformIdentity;
					metrosLabel1.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);	
				}
				
				break;
			case 2:
				
				[bussolaView addSubview:setaImage2]; 
				
				setaImage2.transform = CGAffineTransformIdentity;
				setaImage2.center = CGPointMake(CENTRO);
				setaImage2.transform = CGAffineTransformMakeRotation(anguloItem);
				
				if(asDegrees >= -1.50 && asDegrees <= -0.01)
				{
					tituloLabel2.transform = CGAffineTransformIdentity;
					tituloLabel2.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
					metrosLabel2.transform = CGAffineTransformIdentity;
					metrosLabel2.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
				}
				else if(asDegrees >= 0.00 && asDegrees <= 1.50)
				{
					tituloLabel2.transform = CGAffineTransformIdentity;
					tituloLabel2.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
					metrosLabel2.transform = CGAffineTransformIdentity;
					metrosLabel2.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
				}
				else if(asDegrees >= 1.50 && asDegrees <= 2.99)
				{
					tituloLabel2.transform = CGAffineTransformIdentity;
					tituloLabel2.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);
					metrosLabel2.transform = CGAffineTransformIdentity;
					metrosLabel2.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);
				}
				else if(asDegrees <= -1.50 || asDegrees >= -2.99)
				{
					tituloLabel2.transform = CGAffineTransformIdentity;
					tituloLabel2.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);
					metrosLabel2.transform = CGAffineTransformIdentity;
					metrosLabel2.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);	
				}
				
				break;
			case 3:
				
				[bussolaView addSubview:setaImage3]; 
				
				setaImage3.transform = CGAffineTransformIdentity;
				setaImage3.center = CGPointMake(CENTRO);
				setaImage3.transform = CGAffineTransformMakeRotation(anguloItem);
				
				if(asDegrees >= -1.50 && asDegrees <= -0.01)
				{
					tituloLabel3.transform = CGAffineTransformIdentity;
					tituloLabel3.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
					metrosLabel3.transform = CGAffineTransformIdentity;
					metrosLabel3.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
				}
				else if(asDegrees >= 0.00 && asDegrees <= 1.50)
				{
					tituloLabel3.transform = CGAffineTransformIdentity;
					tituloLabel3.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
					metrosLabel3.transform = CGAffineTransformIdentity;
					metrosLabel3.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
				}
				else if(asDegrees >= 1.50 && asDegrees <= 2.99)
				{
					tituloLabel3.transform = CGAffineTransformIdentity;
					tituloLabel3.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);
					metrosLabel3.transform = CGAffineTransformIdentity;
					metrosLabel3.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);
				}
				else if(asDegrees <= -1.50 || asDegrees >= -2.99)
				{
					tituloLabel3.transform = CGAffineTransformIdentity;
					tituloLabel3.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);
					metrosLabel3.transform = CGAffineTransformIdentity;
					metrosLabel3.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);	
				}
				
				break;
			case 4:
				
				[bussolaView addSubview:setaImage4]; 
				
				setaImage4.transform = CGAffineTransformIdentity;
				setaImage4.center = CGPointMake(CENTRO);
				setaImage4.transform = CGAffineTransformMakeRotation(anguloItem);
				
				if(asDegrees >= -1.50 && asDegrees <= -0.01)
				{
					tituloLabel4.transform = CGAffineTransformIdentity;
					tituloLabel4.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
					metrosLabel4.transform = CGAffineTransformIdentity;
					metrosLabel4.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
				}
				else if(asDegrees >= 0.00 && asDegrees <= 1.50)
				{
					tituloLabel4.transform = CGAffineTransformIdentity;
					tituloLabel4.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
					metrosLabel4.transform = CGAffineTransformIdentity;
					metrosLabel4.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
				}
				else if(asDegrees >= 1.50 && asDegrees <= 2.99)
				{
					tituloLabel4.transform = CGAffineTransformIdentity;
					tituloLabel4.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);
					metrosLabel4.transform = CGAffineTransformIdentity;
					metrosLabel4.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);
				}
				else if(asDegrees <= -1.50 || asDegrees >= -2.99)
				{
					tituloLabel4.transform = CGAffineTransformIdentity;
					tituloLabel4.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);
					metrosLabel4.transform = CGAffineTransformIdentity;
					metrosLabel4.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);	
				}
				
				break;
			case 5:
				
				[bussolaView addSubview:setaImage5];
				
				setaImage5.transform = CGAffineTransformIdentity;
				setaImage5.center = CGPointMake(CENTRO);
				setaImage5.transform = CGAffineTransformMakeRotation(anguloItem);
				
				if(asDegrees >= -1.50 && asDegrees <= -0.01)
				{
					tituloLabel5.transform = CGAffineTransformIdentity;
					tituloLabel5.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
					metrosLabel5.transform = CGAffineTransformIdentity;
					metrosLabel5.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
				}
				else if(asDegrees >= 0.00 && asDegrees <= 1.50)
				{
					tituloLabel5.transform = CGAffineTransformIdentity;
					tituloLabel5.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
					metrosLabel5.transform = CGAffineTransformIdentity;
					metrosLabel5.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
				}
				else if(asDegrees >= 1.50 && asDegrees <= 2.99)
				{
					tituloLabel5.transform = CGAffineTransformIdentity;
					tituloLabel5.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);
					metrosLabel5.transform = CGAffineTransformIdentity;
					metrosLabel5.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);
				}
				else if(asDegrees <= -1.50 || asDegrees >= -2.99)
				{
					tituloLabel5.transform = CGAffineTransformIdentity;
					tituloLabel5.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);
					metrosLabel5.transform = CGAffineTransformIdentity;
					metrosLabel5.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);	
				}
				
				break;
			case 6:
				
				[bussolaView addSubview:setaImage6]; 
				
				setaImage6.transform = CGAffineTransformIdentity;
				setaImage6.center = CGPointMake(CENTRO);
				setaImage6.transform = CGAffineTransformMakeRotation(anguloItem);
				
				if(asDegrees >= -1.50 && asDegrees <= -0.01)
				{
					tituloLabel6.transform = CGAffineTransformIdentity;
					tituloLabel6.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
					metrosLabel6.transform = CGAffineTransformIdentity;
					metrosLabel6.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
				}
				else if(asDegrees >= 0.00 && asDegrees <= 1.50)
				{
					tituloLabel6.transform = CGAffineTransformIdentity;
					tituloLabel6.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
					metrosLabel6.transform = CGAffineTransformIdentity;
					metrosLabel6.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
				}
				else if(asDegrees >= 1.50 && asDegrees <= 2.99)
				{
					tituloLabel6.transform = CGAffineTransformIdentity;
					tituloLabel6.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);
					metrosLabel6.transform = CGAffineTransformIdentity;
					metrosLabel6.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);
				}
				else if(asDegrees <= -1.50 || asDegrees >= -2.99)
				{
					tituloLabel6.transform = CGAffineTransformIdentity;
					tituloLabel6.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);
					metrosLabel6.transform = CGAffineTransformIdentity;
					metrosLabel6.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);	
				}
				
				break;
			case 7:
				
				[bussolaView addSubview:setaImage7]; 
				
				setaImage7.transform = CGAffineTransformIdentity;
				setaImage7.center = CGPointMake(CENTRO);
				setaImage7.transform = CGAffineTransformMakeRotation(anguloItem);
				
				if(asDegrees >= -1.50 && asDegrees <= -0.01)
				{
					tituloLabel7.transform = CGAffineTransformIdentity;
					tituloLabel7.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
					metrosLabel7.transform = CGAffineTransformIdentity;
					metrosLabel7.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
				}
				else if(asDegrees >= 0.00 && asDegrees <= 1.50)
				{
					tituloLabel7.transform = CGAffineTransformIdentity;
					tituloLabel7.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
					metrosLabel7.transform = CGAffineTransformIdentity;
					metrosLabel7.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
				}
				else if(asDegrees >= 1.50 && asDegrees <= 2.99)
				{
					tituloLabel7.transform = CGAffineTransformIdentity;
					tituloLabel7.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);
					metrosLabel7.transform = CGAffineTransformIdentity;
					metrosLabel7.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);
				}
				else if(asDegrees <= -1.50 || asDegrees >= -2.99)
				{
					tituloLabel7.transform = CGAffineTransformIdentity;
					tituloLabel7.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);
					metrosLabel7.transform = CGAffineTransformIdentity;
					metrosLabel7.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);	
				}
				
				break;
			case 8:
				
				[bussolaView addSubview:setaImage8]; 
				
				setaImage8.transform = CGAffineTransformIdentity;
				setaImage8.center = CGPointMake(CENTRO);
				setaImage8.transform = CGAffineTransformMakeRotation(anguloItem);
				
				if(asDegrees >= -1.50 && asDegrees <= -0.01)
				{
					tituloLabel8.transform = CGAffineTransformIdentity;
					tituloLabel8.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
					metrosLabel8.transform = CGAffineTransformIdentity;
					metrosLabel8.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
				}
				else if(asDegrees >= 0.00 && asDegrees <= 1.50)
				{
					tituloLabel8.transform = CGAffineTransformIdentity;
					tituloLabel8.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
					metrosLabel8.transform = CGAffineTransformIdentity;
					metrosLabel8.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
				}
				else if(asDegrees >= 1.50 && asDegrees <= 2.99)
				{
					tituloLabel8.transform = CGAffineTransformIdentity;
					tituloLabel8.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);
					metrosLabel8.transform = CGAffineTransformIdentity;
					metrosLabel8.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);
				}
				else if(asDegrees <= -1.50 || asDegrees >= -2.99)
				{
					tituloLabel8.transform = CGAffineTransformIdentity;
					tituloLabel8.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);
					metrosLabel8.transform = CGAffineTransformIdentity;
					metrosLabel8.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);	
				}
				
				break;
			case 9:
				
				[bussolaView addSubview:setaImage9]; 
				
				setaImage9.transform = CGAffineTransformIdentity;
				setaImage9.center = CGPointMake(CENTRO);
				setaImage9.transform = CGAffineTransformMakeRotation(anguloItem);
				
				if(asDegrees >= -1.50 && asDegrees <= -0.01)
				{
					tituloLabel9.transform = CGAffineTransformIdentity;
					tituloLabel9.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
					metrosLabel9.transform = CGAffineTransformIdentity;
					metrosLabel9.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
				}
				else if(asDegrees >= 0.00 && asDegrees <= 1.50)
				{
					tituloLabel9.transform = CGAffineTransformIdentity;
					tituloLabel9.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
					metrosLabel9.transform = CGAffineTransformIdentity;
					metrosLabel9.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_COR);
				}
				else if(asDegrees >= 1.50 && asDegrees <= 2.99)
				{
					tituloLabel9.transform = CGAffineTransformIdentity;
					tituloLabel9.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);
					metrosLabel9.transform = CGAffineTransformIdentity;
					metrosLabel9.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);
				}
				else if(asDegrees <= -1.50 || asDegrees >= -2.99)
				{
					tituloLabel9.transform = CGAffineTransformIdentity;
					tituloLabel9.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);
					metrosLabel9.transform = CGAffineTransformIdentity;
					metrosLabel9.transform = CGAffineTransformMakeRotation(CENTRO_LABEL_INV);	
				}
				
				break;
			default:
				break;
		}
		
		[bussolaView addSubview:myImage]; 
		myImage.transform = CGAffineTransformIdentity;
		myImage.center = CGPointMake(CENTRO);
		myImage.transform = CGAffineTransformMakeRotation(-1 * mHeading * M_PI / 180.0);
	}
	
}

#pragma mark -
#pragma mark Objeto

- (void) initWithObject:(NSMutableArray *) array
{
	DictDados = [[NSMutableDictionary alloc] init];
	
	NSString *Id, *Nome, *latitude, *longitude, *distancia, *aLat, *aLon;
	arrayDados = [[NSMutableArray alloc] init];
	
	NSLog(@"array: %@", array);
	int i;
	for (i=0; i<[array count]; i++) {
		
		
		farmObj = [array objectAtIndex:i];
		arrLL = [farmObj.farmLLString componentsSeparatedByString:@","];
		
		aLat = [arrLL objectAtIndex:0];
		fLat = [aLat floatValue];
		
		aLon = [arrLL objectAtIndex:1];
		fLon = [aLon floatValue];
		distancia = [NSString stringWithFormat:@"%.2f Km", [self CalculateDistance:latitudeAtual Lon:longitudeAtual Lat:fLat Long:fLon indice:i]];
		//NSLog(@"farmObj.farmNome %@", farmObj.farmNome);
		
		Id = [NSString stringWithFormat:@"%d", farmObj.farmID];
		Nome = farmObj.farmNome;
		latitude = [NSString stringWithFormat:@"%f", fLat];
		longitude = [NSString stringWithFormat:@"%f", fLon];
		
		NSDictionary *myDictConfig = [NSDictionary dictionaryWithObjectsAndKeys:
									  Id, @"id",
									  Nome, @"nome",
									  latitude, @"latitude",
									  longitude, @"longitude",
									  distancia, @"distancia",
									  nil];
		
		[arrayDados addObject:myDictConfig];	
		[myDictConfig release];

	}
	
	NSArray *sortedArray = [[NSArray alloc] init];
	sortedArray = [arrDistancia sortedArrayUsingSelector:@selector(compare:)];
	//NSLog(@"sortedArray: %@", sortedArray);
	//[sortedArray release];
	int valArr = [arrayDados count] > 9 ? 10 : [arrayDados count];
 
	for (int i = 0 ; i<valArr; i++) {
		
		NSString *verIndice = [sortedArray objectAtIndex:i];
		int val = [verIndice rangeOfString:@" "].location;
		verIndice = [verIndice substringFromIndex:val];
		//NSLog(@"%d", [verIndice intValue]);
		val = [verIndice intValue];
		[DictDados setObject:[[arrayDados objectAtIndex:val] copy] forKey:[NSString stringWithFormat:@"%d",i]];
		//NSLog(@"DictDados %@", DictDados);
	}
	
	if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown) {
		[self viewBussola];
	} else {
		
		[self viewAR];
		arView = YES;
	}

}

#pragma mark UIDeviceOrientation Notifications

- (void)deviceOrientationDidChange:(NSNotification *)notification {
	
	orientation = [[UIDevice currentDevice] orientation];
	if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown) {
		[self viewBussola];
		[self.arController.overlayView bringSubviewToFront:self.bussolaView];
	} else if (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight){
		
		[self.arController.overlayView sendSubviewToBack:self.bussolaView];
		[self.bussolaView removeFromSuperview];
		[self viewAR];
		arView = YES;
	}
	[self criaTabBar];

}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
	
	// Parar com as atualizacoes de localizacao para economizar bateria
	[manager stopUpdatingLocation];
	
	latitudeAtual = newLocation.coordinate.latitude;
	longitudeAtual = newLocation.coordinate.longitude;

}

@end
